<template>
  <el-container>
    <el-main>
      <div class="search-container">
        <el-form ref="form" label-position="top" :rules="rules" :model="form" label-width="80px">
          <h2 style="text-align: center; color: #7d8995">
            <i class="el-icon-edit-outline" />写博客</h2>
          <el-form-item prop="title">
            <span slot="label" style="color: #333333;  font-weight: bold">标题：</span>
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item prop="content">
            <span slot="label" style="color: #333333;  font-weight: bold">内容：</span>
            <mavon-editor
              ref="md"
              v-model="form.content"
              :autofocus="false"
              placeholder="支持markdown和katex公式 "
              @imgAdd="imgAdd"
            />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="form.isPublic" :true-label="1" :false-label="0">公开</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="success" style="font-weight: bold" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { newBlog } from '@/networks/blog'
import { imgAdd } from '@/networks/info'

import { dataURLtoFile } from '@/utils/utils'
export default {
  name: 'NewBlog',
  data() {
    return {
      form: {
        content: '',
        title: '',
        isPublic: 0
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return false
        newBlog(this.form)
          .then(res => {
            const data = res.data
            this.$message.success(data.msg)
            this.$router.push('/blog')
            this.$bus.emit('new-blog')
          })
      })
    },
    imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      const form = new FormData()

      this.imgUrl = URL.createObjectURL($file, { quality: 0 })
      // eslint-disable-next-line no-undef
      lrz(this.imgUrl).then(rst => {
        // 压缩后文件大小
        const tempFile = dataURLtoFile(rst.base64, $file.name)
        tempFile.uid = rst.origin.uid
        form.append('file', tempFile)
        imgAdd(form).then(res => {
          this.$refs.md.$img2Url(pos, res.data.data)
        })
      })
    }
  }
}
</script>

<style scoped>
  .search-container {
    margin-left: auto !important;
    margin-right: auto !important;
    width: 1200px;
    height: auto;
    background-color: #ffffff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

  }

  .el-form {
    padding: 20px;
  }
</style>
